package com.niubi.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.niubi.yygh.common.exception.YyghException;
import com.niubi.yygh.hosp.repository.ScheduleRepository;
import com.niubi.yygh.hosp.service.DepartmentService;
import com.niubi.yygh.hosp.service.HospitalService;
import com.niubi.yygh.hosp.service.HospitalSetService;
import com.niubi.yygh.hosp.service.ScheduleService;
import com.niubi.yygh.model.hosp.BookingRule;
import com.niubi.yygh.model.hosp.Department;
import com.niubi.yygh.model.hosp.Hospital;
import com.niubi.yygh.model.hosp.Schedule;
import com.niubi.yygh.vo.hosp.BookingScheduleRuleVo;
import com.niubi.yygh.vo.hosp.ScheduleOrderVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class ScheduleServiceImpl implements ScheduleService {
  @Autowired
  DepartmentService departmentService;

  @Autowired
  HospitalService hospitalService;

  @Autowired
  MongoTemplate mongoTemplate;

  @Autowired
  private ScheduleRepository scheduleRepository;

  @Override
  public void saveSchedule(Map<String, Object> map) {
    String jsonString = JSONObject.toJSONString(map);
    Schedule schedule = JSONObject.parseObject(jsonString, Schedule.class);
    Schedule scheduleExist = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());
    if (scheduleExist != null) {
      schedule.setId(scheduleExist.getId());
      schedule.setCreateTime(scheduleExist.getCreateTime());
      schedule.setUpdateTime(new Date());
      scheduleRepository.save(schedule);
    } else {
      schedule.setCreateTime(new Date());
      schedule.setUpdateTime(new Date());
      scheduleRepository.save(schedule);
    }
  }

  @Override
  public Page<Schedule> selectPage(int page, int limit) {
    Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
    PageRequest pageable = PageRequest.of(page - 1, limit, sort);
    Schedule schedule = new Schedule();
    Example<Schedule> example = Example.of(schedule);
    Page<Schedule> pageModel = scheduleRepository.findAll(example, pageable);
    return pageModel;
  }

  @Override
  public void remove(String hoscode, String hosScheduleId) {
    Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
    if (schedule != null) {
      scheduleRepository.deleteById(schedule.getId());
    }
  }

  @Override
  public Map<String, Object> getScheduleRule(long page, long limit, String hoscode, String depcode) {
    Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
    Aggregation aggregation = Aggregation.newAggregation(
            Aggregation.match(criteria),
            Aggregation.group("workDate").first("workDate")
                    .as("workDate")
                    .count().as("doCount")
                    .sum("reservedNumber").as("reservedNumber")
                    .sum("availableNumber").as("availableNumber"),
            Aggregation.sort(Sort.Direction.ASC, "workDate"),
            Aggregation.skip((page - 1) * limit),
            Aggregation.limit(limit)
    );
    AggregationResults<BookingScheduleRuleVo> aggResult = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
    List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggResult.getMappedResults();

    Aggregation aggtotal = Aggregation.newAggregation(
            Aggregation.match(criteria),
            Aggregation.group("workDate")
    );
    AggregationResults<BookingScheduleRuleVo> totalAggResults = mongoTemplate.aggregate(aggtotal,
            Schedule.class, BookingScheduleRuleVo.class);
    List<BookingScheduleRuleVo> list = totalAggResults.getMappedResults();
    int total = list.size();

    for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
      Date workDate = bookingScheduleRuleVo.getWorkDate();
      String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
      bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
    }

    Map<String, Object> result = new HashMap<>();
    result.put("bookingScheduleRuleList",bookingScheduleRuleVoList);
    result.put("total",total);

    Hospital hosp = hospitalService.getByHoscode(hoscode);
    String hosName = hosp.getHosname();
    Map<String, String> baseMap = new HashMap<>();
    baseMap.put("hosname",hosName);
    result.put("baseMap",baseMap);
    return result;
  }

  @Override
  public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
    Date date = new DateTime(workDate).toDate();
    List<Schedule> list = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,date);
    list.stream().forEach(item->{
      this.packageSchedule(item);
    });
    return list;
  }

  @Override
  public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
    //获取预约规则
    Hospital hospital = hospitalService.getByHoscode(hoscode);
    if (hospital ==null){
      throw new YyghException(20001,"医院信息不存在");
    }
    BookingRule bookingRule = hospital.getBookingRule();
    //根据当前日期和预约周期,把所有显示日期获取到
    IPage<Date> iPage = this.getDateList(page,limit,bookingRule);
    List<Date> dateList = iPage.getRecords();

    //根据医院编号可是编号和所有可以显示的日期,作为条件进行聚合查询
    Criteria criteria = Criteria.where("hoscode").in(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);
    Aggregation agg = Aggregation.newAggregation(
            Aggregation.match(criteria),
            Aggregation.group("workDate")
                    .first("workDate").as("workDate").count().as("docCount")
                    .sum("availableNumber").as("availableNumber")
                    .sum("reservedNumber").as("reservedNumber"));
    AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
    List<BookingScheduleRuleVo> scheduleList = aggregationResults.getMappedResults();
    //合并数据 将统计数据ScheduleVo根据“安排日期”合并到BookingRuleVo
    Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
    if(!CollectionUtils.isEmpty(scheduleList)) {
      scheduleVoMap = scheduleList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo));
    }
    //获取可预约排班规则
    List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
    for(int i=0, len=dateList.size(); i<len; i++) {
      Date date = dateList.get(i);

      BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
      if(null == bookingScheduleRuleVo) { // 说明当天没有排班医生
        bookingScheduleRuleVo = new BookingScheduleRuleVo();
        //就诊医生人数
        bookingScheduleRuleVo.setDocCount(0);
        //科室剩余预约数  -1表示无号
        bookingScheduleRuleVo.setAvailableNumber(-1);
      }
      bookingScheduleRuleVo.setWorkDate(date);
      bookingScheduleRuleVo.setWorkDateMd(date);
      //计算当前预约日期为周几
      //计算当前预约日期为周几
      String dayOfWeek = this.getDayOfWeek(new DateTime(date));
      bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);

      //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
      if(i == len-1 && page == iPage.getPages()) {
        bookingScheduleRuleVo.setStatus(1);
      } else {
        bookingScheduleRuleVo.setStatus(0);
      }
      //当天预约如果过了停号时间， 不能预约
      if(i == 0 && page == 1) {
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        if(stopTime.isBeforeNow()) {
          //停止预约
          bookingScheduleRuleVo.setStatus(-1);
        }
      }
      bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
    }

    Map<String,Object> result = new HashMap<>();
    result.put("bookingScheduleList", bookingScheduleRuleVoList);
    result.put("total", iPage.getTotal());
    //其他基础数据
    Map<String, String> baseMap = new HashMap<>();
    //医院名称
    Hospital hospital1 = hospitalService.getByHoscode(hoscode);
    baseMap.put("hosname", hospital1.getHosname());
    //科室
    Department department =departmentService.getDeptName(hoscode, depcode);
    //大科室名称
    baseMap.put("bigname", department.getBigname());
    //科室名称
    baseMap.put("depname", department.getDepname());
    //月
    baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
    //放号时间
    baseMap.put("releaseTime", bookingRule.getReleaseTime());
    //停号时间
    baseMap.put("stopTime", bookingRule.getStopTime());
    result.put("baseMap", baseMap);
      return result;
  }

  @Override
  public Schedule getById(String id) {
    Schedule schedule = scheduleRepository.findById(id).get();
    return this.packageSchedule(schedule);
  }

  @Override
  public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
    //根据排版ID查询
    Schedule schedule = this.getById(scheduleId);
    Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
    BookingRule bookingRule = hospital.getBookingRule();
    ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
    scheduleOrderVo.setHoscode(schedule.getHoscode());
    scheduleOrderVo.setHosname(hospital.getHosname());
    scheduleOrderVo.setDepcode(schedule.getDepcode());
    scheduleOrderVo.setDepname(departmentService.getDeptName(schedule.getHoscode(), schedule.getDepcode()).getDepname());
    scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
    scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
    scheduleOrderVo.setTitle(schedule.getTitle());
    scheduleOrderVo.setReserveDate(schedule.getWorkDate());
    scheduleOrderVo.setReserveTime(schedule.getWorkTime());
    scheduleOrderVo.setAmount(schedule.getAmount());
    //退号截止天数（如：就诊前一天为-1，当天为0）
    int quitDay = bookingRule.getQuitDay();
    DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
    scheduleOrderVo.setQuitTime(quitTime.toDate());

    //预约开始时间
    DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
    scheduleOrderVo.setStartTime(startTime.toDate());

    //预约截止时间
    DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
    scheduleOrderVo.setEndTime(endTime.toDate());

    //当天停止挂号时间
    DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
    scheduleOrderVo.setStopTime(stopTime.toDate());
    return scheduleOrderVo;
  }

  @Override
  public void updateSchedule(Schedule schedule) {
    schedule.setUpdateTime(new Date());
    scheduleRepository.save(schedule);
  }

  //根据当前日期和预约周期,把所有显示日期获取到,分页显示
  private IPage<Date> getDateList(Integer page, Integer limit, BookingRule bookingRule) {
    DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
    Integer cycle = bookingRule.getCycle();
    if (releaseTime.isBeforeNow()) {cycle +=1;}
    List<Date> dateList = new ArrayList<>();
    for (int i = 0;i<cycle;i++){
      DateTime curDateTime = new DateTime().plusDays(i);
      String dateString = curDateTime.toString("yyyy-MM-dd");
      dateList.add(new DateTime(dateString).toDate());
    }
    List<Date> pageDateList = new ArrayList<>();
    int start = (page-1)*limit;
    int end = (page-1)*limit+limit;
    if (end>dateList.size()) {end = dateList.size();}
    for (int i = start;i<end;i++){
      pageDateList.add(dateList.get(i));
    }

    IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page, 7, dateList.size());
    iPage.setRecords(pageDateList);
    return iPage;
  }

  /**
   * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
   */
  private DateTime getDateTime(Date date, String timeString) {
    String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
    DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
    return dateTime;
  }

  private Schedule packageSchedule(Schedule schedule) {
    Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
    String hosname = hospital.getHosname();

    Department department = departmentService.getDeptName(schedule.getHoscode(),schedule.getDepcode());
    String depname = department.getDepname();

    String dayOfWeek = this.getDayOfWeek(new DateTime(schedule.getWorkDate()));

    schedule.getParam().put("hosname",hosname);
    schedule.getParam().put("depname",depname);
    schedule.getParam().put("dayOfWeek",dayOfWeek);

    return schedule;
  }

  private String getDayOfWeek(DateTime dateTime) {
    String dayOfWeek = "";
    switch (dateTime.getDayOfWeek()) {
      case DateTimeConstants.SUNDAY:
        dayOfWeek = "周日";
        break;
      case DateTimeConstants.MONDAY:
        dayOfWeek = "周一";
        break;
      case DateTimeConstants.TUESDAY:
        dayOfWeek = "周二";
        break;
      case DateTimeConstants.WEDNESDAY:
        dayOfWeek = "周三";
        break;
      case DateTimeConstants.THURSDAY:
        dayOfWeek = "周四";
        break;
      case DateTimeConstants.FRIDAY:
        dayOfWeek = "周五";
        break;
      case DateTimeConstants.SATURDAY:
        dayOfWeek = "周六";
      default:
        break;
    }
    return dayOfWeek;
  }
}